package com.xingyun.info_manager.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.xingyun.info_manager.entity.*;
import com.xingyun.info_manager.service.IPatInfoWxService;
import com.xingyun.info_manager.service.IPatientNetService;
import com.xingyun.info_manager.util.JSONChange;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Classname PatientNetController
 * @Description 网络渠道
 * @Date 2020/5/26 16:09
 * @Created by You
 */
@Controller
public class PatientNetController {

    @Autowired
    private IPatientNetService patientNetService;

    @Autowired
    private IPatInfoWxService patInfoWxService;

    /**
     * 查询所有网络渠道登记病人信息
     */
    @ResponseBody
    @RequestMapping("/patnet/findall")
    public String findAllUserDemo(HttpServletRequest request, HttpSession session) throws JsonProcessingException {
        //查询条件
        String patName = request.getParameter("name");
        String userMobile = request.getParameter("phone");
        int patState = Integer.parseInt(request.getParameter("patState"));
        int isComeHospital =  Integer.parseInt(request.getParameter("isComeHospital"));
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");


        //获取登录用户信息，从session中取出
        AdminUser admin = (AdminUser) session.getAttribute("admin");
        //获取渠道id
        int channelId = admin.getChannelId();

        //用于传参实体类
        ParasBean parasBean = new ParasBean();
        parasBean.setChannelId(channelId);
        parasBean.setPatName(patName);
        parasBean.setUserMobile(userMobile);
        parasBean.setPatState(patState);
        parasBean.setIsComeHospital(isComeHospital);
        try {
            if(!StringUtils.isBlank(startTime)){//不为空则转换并且赋值
                parasBean.setStartTime(sdf.parse(startTime));
            }
            if(!StringUtils.isBlank(endTime)){
                parasBean.setEndTime(sdf.parse(endTime));
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }

        Integer currPage;//当前页数
        if(!StringUtils.isBlank(request.getParameter("currPage"))) {
            currPage = Integer.valueOf(request.getParameter("currPage"));
        } else {
            currPage = 1;
        }
        parasBean.setCurrPage(currPage);

        Integer pageSize;//每页展示条数
        if(!StringUtils.isBlank(request.getParameter("pageSize"))) {
            pageSize = Integer.valueOf(request.getParameter("pageSize"));
        } else {
            pageSize = 5;
        }
        parasBean.setPageSize(pageSize);
        //返回的响应对象
        ReturnBeans<List<PatientInfo>> returnBean = new ReturnBeans<List<PatientInfo>>();
        returnBean.setCurrPage(currPage);
        returnBean.setPageSize(pageSize);
        //根据页数和显示条数计算分页起始位置
        int initPage = (currPage - 1) * pageSize;
        parasBean.setInitPage(initPage);

        /**
         * 查询总条数
         */
        int count = patientNetService.findCount(parasBean);
        returnBean.setCount(count);
        System.out.println("------ "+initPage+","+pageSize+","+count);

        /**
         * 查询详细信息
         */
        List<PatientInfo> patList =  patientNetService.findAllPat(parasBean);
//        request.setAttribute("patList",patList);
        returnBean.setData(patList);
        request.setAttribute("page",returnBean);
        System.out.println(" - --" + JSONChange.objToJson(returnBean));
        //将对象转为json字符串返回
        return JSONChange.objToJson(returnBean);
    }

    /**
     * 修改用户状态：正常/作废
     * @param request
     * @return
     * @throws JsonProcessingException
     */
    @ResponseBody
    @RequestMapping("/patnet/chgstate")
    public String changeState(HttpServletRequest request, HttpSession session) throws JsonProcessingException {

        ParasBean parasBean = new ParasBean();
        parasBean.setId(Integer.parseInt(request.getParameter("id")));
        //当前用户状态
        int patState = Integer.parseInt(request.getParameter("patState"));
        if(patState == 1){
            patState = 2;//修改后数据状态（2，作废、1：启用）
        } else {
            patState = 1;//修改后数据状态（2，作废、1：启用）
        }
        parasBean.setPatState(patState);
        System.out.println("-----------" + parasBean);

        //返回的响应对象
        ReturnBeans returnBean = new ReturnBeans<>();

        int res = patientNetService.changeState(parasBean);
        if(res == 0){
            returnBean.setCode(1);
            returnBean.setMsg("修改失败");
        }
        //将对象转为json字符串返回
        return JSONChange.objToJson(returnBean);
    }

    /**
     * 根据id获取用户信息
     * @param request
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping("/patnet/infomsg")
    public String getInfoMsg(HttpServletRequest request, HttpSession session) throws JsonProcessingException {
        //获取病人id
        int id = Integer.parseInt(request.getParameter("id"));
        //根据用户id查询用户信息
        PatientInfo patientInfo = patientNetService.findById(id);
        request.setAttribute("patientInfo",  patientInfo);

        //跳转到详细信息页面
        return "patient_net/pat_info_msg";
    }

    /**
     * 新增
     * @param request
     * @return
     * @throws JsonProcessingException
     */
    @ResponseBody
    @RequestMapping("/patnet/add")
    public String addInfo(HttpServletRequest request, HttpSession session) throws JsonProcessingException {

        PatientInfo patientInfo = new PatientInfo();
        patientInfo.setPatName(request.getParameter("patName"));

        if(!StringUtils.isBlank(request.getParameter("age"))){
            patientInfo.setAge(Integer.parseInt(request.getParameter("age")));
        }
        patientInfo.setPhone(request.getParameter("phone"));
        //根据手机号查询此用户是否微信预约并且到院
        if(StringUtils.isBlank(request.getParameter("phone"))){//手机号若为空
            patientInfo.setIsComeHospital(2);//手机号若为空，则未到院
        } else {//不为空，查询此用户
            List<PatInfoWx> patInfoWxList = patInfoWxService.getInfoByPhone(request.getParameter("phone"));

            if(patInfoWxList == null || patInfoWxList.size() == 0){//用户不存在说明尚未进行微信预约
                patientInfo.setIsComeHospital(2);//用户不存在，则未到院
            } else {
                PatInfoWx patInfoWx = patInfoWxList.get(0);
                System.out.println("patInfoWxList.get(0): " + patInfoWx);
                //判断此手机号用户是否已经到院，根据是否生成医院pat_id来判断
                //如果hisPatId存在则说明用户已到院，不存在则表示未到院
                String hisPatId = patInfoWx.getHisPatId();
                if(StringUtils.isBlank(hisPatId)){
                    patientInfo.setIsComeHospital(2);//hisPatId不存在则表示未到院
                } else {
                    patientInfo.setIsComeHospital(1);//hisPatId存在则表示已到院
                }

            }
        }

        patientInfo.setWechat(request.getParameter("wechat"));
        patientInfo.setGender(Integer.parseInt(request.getParameter("gender")));
        patientInfo.setAppointDept(request.getParameter("appointDept"));
        patientInfo.setDiseaseEntities(request.getParameter("diseaseEntities"));
        patientInfo.setConsultType(Integer.parseInt(request.getParameter("consultType")));

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //预约时间
        String appointTime = request.getParameter("appointTime");
        try {
            if(!StringUtils.isBlank(appointTime)){
                patientInfo.setAppointTime(sdf.parse(appointTime));
            }
            } catch (ParseException e) {
                e.printStackTrace();
        }
        patientInfo.setAttendDoctor(request.getParameter("attendDoctor"));

        patientInfo.setSubsequentVisit(Integer.parseInt(request.getParameter("subsequentVisit")));
        patientInfo.setIsInHospital(Integer.parseInt(request.getParameter("isInHospital")));
        patientInfo.setTreatmentItems(request.getParameter("treatmentItems"));
        String totalMoney = request.getParameter("totalMoney");
        if(!StringUtils.isBlank(totalMoney)){
            patientInfo.setTotalMoney(BigDecimal.valueOf(Double.parseDouble(totalMoney)));
        }
        patientInfo.setReturnVisit(Integer.parseInt(request.getParameter("returnVisit")));
        patientInfo.setPatSituation(request.getParameter("patSituation"));
        patientInfo.setPatIntention(request.getParameter("patIntention"));
        patientInfo.setNotComeReason(request.getParameter("notComeReason"));
        System.out.println("----------"+patientInfo);

        //获取登录用户信息
        AdminUser admin = (AdminUser) session.getAttribute("admin");
        //获取创建人登录名
        patientInfo.setCreateUser(admin.getUserName());
        //获取创建人渠道名称
        patientInfo.setCreateChannelNo(admin.getChannelId());
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取创建时间
        patientInfo.setCreateTime(new Date());

        //返回的响应对象
        ReturnBeans returnBean = new ReturnBeans<>();

        int res = patientNetService.addInfo(patientInfo);
        if(res == 0){
            returnBean.setCode(1);
            returnBean.setMsg("新增失败");
        }
        //将对象转为json字符串返回
        return JSONChange.objToJson(returnBean);
    }


    /**
     * 根据手机号获取用户信息
     * @param request
     * @return
     * @throws JsonProcessingException
     */
    @ResponseBody
    @RequestMapping("/patnet/phonemsg")
    public String getInfoByPhone(HttpServletRequest request, HttpSession session) throws JsonProcessingException {
        //获取病人phone
        String phone = request.getParameter("phone");

        //获取id(id=0时为新增查询过滤不处理，id!=0时为修改过滤，需处理)
        int id = Integer.parseInt(request.getParameter("id"));

        //返回的响应对象
        ReturnBeans returnBean = new ReturnBeans<>();

        int res = patientNetService.getInfoByPhone(phone,id);
        if(res > 0){
            returnBean.setCode(1);
            returnBean.setMsg("手机号已存在!");
        }
        //将对象转为json字符串返回
        return JSONChange.objToJson(returnBean);
    }

    /**
     * 跳转到修改页
     * @param request
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping("/patnet/toUpdate")
    public String toUpdatePage(HttpServletRequest request, HttpSession session) {
        //获取病人id
        int id = Integer.parseInt(request.getParameter("id"));

        //获取登录用户信息
        AdminUser admin = (AdminUser) session.getAttribute("admin");
        //获取登录名
        String adminUser = admin.getUserName();
        //获取登录渠道id
        int channelId = admin.getChannelId();

        //根据用户id查询用户信息
        PatientInfo patientInfo = patientNetService.findById(id);
        request.setAttribute("patientInfo",  patientInfo);

        /**
         * 若当前登录用户为创建人则允许修改所有信息
         * 若当前登录用户非创建人则只允许修改回访信息
         * 需要比较当前登录用户和信息创建人是否为同一渠道同一人
         */
        //若为同一人则允许跳转到全部信息修改页
        if(adminUser.equals(patientInfo.getCreateUser()) && channelId == patientInfo.getCreateChannelNo()){
            //跳转到详细信息修改页面
            return "patient_net/pat_info_update";
        } else {//若非同一人则跳战到回访信息修改页
            //跳转到回访信息修改页面
            return "patient_net/return_visit";
        }
    }

    /**
     * 修改
     * @param request
     * @return
     * @throws JsonProcessingException
     */
    @ResponseBody
    @RequestMapping("/patnet/update")
    public String updateInfo(HttpServletRequest request, HttpSession session) throws JsonProcessingException {

        PatientInfo patientInfo = new PatientInfo();
        patientInfo.setId(Integer.parseInt(request.getParameter("id")));
        patientInfo.setPatName(request.getParameter("patName"));

        if(!StringUtils.isBlank(request.getParameter("age"))){
            patientInfo.setAge(Integer.parseInt(request.getParameter("age")));
        }
        patientInfo.setPhone(request.getParameter("phone"));
        patientInfo.setWechat(request.getParameter("wechat"));
        patientInfo.setGender(Integer.parseInt(request.getParameter("gender")));
        patientInfo.setIsComeHospital(Integer.parseInt(request.getParameter("isComeHospital")));
        patientInfo.setAppointDept(request.getParameter("appointDept"));
        patientInfo.setDiseaseEntities(request.getParameter("diseaseEntities"));
        patientInfo.setConsultType(Integer.parseInt(request.getParameter("consultType")));

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //预约时间
        String appointTime = request.getParameter("appointTime");
        try {
            if(!StringUtils.isBlank(appointTime)){
                System.out.println("appointTime:" + appointTime);
                patientInfo.setAppointTime(sdf.parse(appointTime));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        patientInfo.setAttendDoctor(request.getParameter("attendDoctor"));

        patientInfo.setSubsequentVisit(Integer.parseInt(request.getParameter("subsequentVisit")));
        patientInfo.setIsInHospital(Integer.parseInt(request.getParameter("isInHospital")));
        patientInfo.setTreatmentItems(request.getParameter("treatmentItems"));
        String totalMoney = request.getParameter("totalMoney");
        if(!StringUtils.isBlank(totalMoney)){
            patientInfo.setTotalMoney(BigDecimal.valueOf(Double.parseDouble(totalMoney)));
        }
        patientInfo.setReturnVisit(Integer.parseInt(request.getParameter("returnVisit")));
        patientInfo.setPatSituation(request.getParameter("patSituation"));
        patientInfo.setPatIntention(request.getParameter("patIntention"));
        patientInfo.setNotComeReason(request.getParameter("notComeReason"));

        //获取登录用户信息
        AdminUser admin = (AdminUser) session.getAttribute("admin");
        //获取修改人登录名
        patientInfo.setUpdateUser(admin.getUserName());
        //获取修改人渠道名称
        patientInfo.setUpdateChannelNo(admin.getChannelId());
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取修改时间
        patientInfo.setUpdateTime(new Date());

        System.out.println("----------"+patientInfo);
        //返回的响应对象
        ReturnBeans returnBean = new ReturnBeans<>();

        int res = patientNetService.updateInfo(patientInfo);
        System.out.println("res:" + res);
        if(res == 0){
            returnBean.setCode(1);
            returnBean.setMsg("修改失败");
        }
        //将对象转为json字符串返回
        return JSONChange.objToJson(returnBean);
    }

    /**
     * 校验是否到院
     */
    @ResponseBody
    @RequestMapping("/patnet/checkOutIsCome")
    public String checkOutIsCome(HttpServletRequest request) throws JsonProcessingException {
        int id = Integer.parseInt(request.getParameter("id"));
        //当前到院状态
        String phone = request.getParameter("phone");

        //返回的响应对象
        ReturnBeans returnBean = new ReturnBeans<>();
        List<PatInfoWx> patInfoWxList = patInfoWxService.getInfoByPhone(phone);
//        System.out.println("patInfoWxList" + patInfoWxList);
        if(patInfoWxList == null || patInfoWxList.size() == 0){//用户不存在说明尚未进行微信预约
            returnBean.setCode(1);
            returnBean.setMsg("此用户尚未微信预约");
            //将对象转为json字符串返回
            return JSONChange.objToJson(returnBean);
        }

        PatInfoWx patInfoWx = patInfoWxList.get(0);
        System.out.println("patInfoWxList.get(0): " + patInfoWx);
//        if(patInfoWx == null){//用户不存在说明尚未进行微信预约
//            returnBean.setCode(1);
//            returnBean.setMsg("此用户尚未微信预约");
//            //将对象转为json字符串返回
//            return JSONChange.objToJson(returnBean);
//        }

        ParasBean parasBean = new ParasBean();
        parasBean.setId(id);

        //判断此手机号用户是否已经到院，根据是否生成医院pat_id来判断
        //如果hisPatId存在则说明用户已到院，不存在则表示未到院
        String hisPatId = patInfoWx.getHisPatId();
        if(StringUtils.isBlank(hisPatId)){
            //当前到院状态,数据状态（1.是 2.否）
            parasBean.setIsComeHospital(2);
            //更改到院状态
            int res = patientNetService.chgIsCome(parasBean);
            if(res == 0){
                returnBean.setCode(1);
                returnBean.setMsg("修改失败");
            }
            returnBean.setMsg("此用户当前未到院");
            //将对象转为json字符串返回
            return JSONChange.objToJson(returnBean);
        } else {
            //当前到院状态,数据状态（1.是 2.否）
            parasBean.setIsComeHospital(1);
            //更改到院状态
            int res = patientNetService.chgIsCome(parasBean);
            if(res == 0){
                returnBean.setCode(1);
                returnBean.setMsg("修改失败");
            }
            returnBean.setMsg("此用户当前已到院");
            //将对象转为json字符串返回
            return JSONChange.objToJson(returnBean);
        }

    }

    /**
     * 更改到院状态
     * 1.是 2.否
     */
    @ResponseBody
    @RequestMapping("/patnet/chgiscome")
    public String chgIsCome(HttpServletRequest request) throws JsonProcessingException {
        ParasBean parasBean = new ParasBean();
        parasBean.setId(Integer.parseInt(request.getParameter("id")));
        //当前到院状态
        int isComeHospital = Integer.parseInt(request.getParameter("isComeHospital"));
        //数据状态（1.是 2.否 9.其他）
        if(isComeHospital == 1){//到院，1的话只改为2
            isComeHospital = 2;
        } else {//2和9都改为1
            isComeHospital = 1;
        }
        parasBean.setIsComeHospital(isComeHospital);
        System.out.println("-----------" + parasBean);

        //返回的响应对象
        ReturnBeans returnBean = new ReturnBeans<>();

        int res = patientNetService.chgIsCome(parasBean);
        if(res == 0){
            returnBean.setCode(1);
            returnBean.setMsg("修改失败");
        }
        //将对象转为json字符串返回
        return JSONChange.objToJson(returnBean);
    }
}
